package com.cqut.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.cqut.dto.LimitShowDTO;
import com.cqut.dto.LoginInfoDTO;
import com.cqut.dto.UserDTO;
import com.cqut.service.IUserService;
import com.cqut.model.User;
import com.cqut.util.ResponseUtil;
import com.cqut.util.StringUtil;
import com.cqut.validInterfaces.GroupForUpdate;
import com.cqut.validInterfaces.GroupForUpdateExtra;


@RestController
@RequestMapping("/api/user")
public class UserController {
    @Resource(name="userService")
    private IUserService userService;

    /**
     * 根据条件搜索筛选列表
     * @param limitShowDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "/searchForUser", method = RequestMethod.GET)
    public ResponseEntity<String> list(
    	UserDTO userDTO, BindingResult uErrors,
        @Validated
        LimitShowDTO limitShowDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        //Map<String, Object> result = new HashMap<String, Object>();

        List<Map<String, Object>> userList = userService.searchForUser(userDTO,limitShowDTO);
        //long count = userService.count();

        //result.put("rows", userList);
        //result.put("total", count);

        return ResponseUtil.getResEntityForGetAndJsonArray(userList);
    }
    
    /**
     * 根据搜索条件进行筛选列表数量
     */
    @RequestMapping(value="/count", method=RequestMethod.GET)
	public ResponseEntity<String> findModulesWithLimit(
			UserDTO userDTO, BindingResult uErrors) {
    	if (uErrors.hasErrors())
			ResponseUtil.getResponseEntityWhenInvalidReqParams();
		JSONObject json = new JSONObject();
		json.put("totalItems", userService.findCountOfUsers(userDTO));
		
		return ResponseUtil.getResEntityForGet(json.toJSONString());
	}
    
    /**
     * 初始化列表
     * @param limitShowDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<String> list(
        @Validated
        LimitShowDTO limitShowDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        //Map<String, Object> result = new HashMap<String, Object>();

        List<Map<String, Object>> userList = userService.loadMaps(null, null, null, null, limitShowDTO.getCurPage(), limitShowDTO.getLimit());
        //long count = userService.count();
        
        //result.put("rows", userList);
        //result.put("total", count);

        return ResponseUtil.getResEntityForGetAndJsonArray(userList);
    }

    /**
     * 根据ID获得用户的基本信息
     * @param userId
     * @return
     */
    @RequestMapping(value = "/detail/{userId}", method = RequestMethod.GET)
    public ResponseEntity<String> show(
    		@PathVariable("userId") 
    		String userId) {
        Map<String, Object> userModel = userService.findMap(userId);

        return ResponseUtil.getResEntityForGetAndJson(userModel);
    }

    /**
     * 新增用户
     * @param userDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "userAdd", method = RequestMethod.POST)
    public ResponseEntity<String> create(
        @Validated
        UserDTO userDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        User userModel = userDTO.toModel();

        return ResponseUtil.getResEntityForPPP(userService.save(userModel));
    }

    /**
     * 编辑用户信息
     * @param userId
     * @param userDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "userUpdate", method = RequestMethod.PUT)
    public ResponseEntity<String> update(
    	/*@PathVariable("userId") 
    	String userId,*/
        @Validated
        UserDTO userDTO, BindingResult errors) {
        User userModel = userDTO.toModel();
        userModel.setUserId(userDTO.userId);
        return ResponseUtil.getResEntityForPPP(userService.update(userModel));
    }

    /**
     * 根据ID删除一个用户
     * @param userId
     * @return
     */
    @RequestMapping(value = "/{userId}", method = RequestMethod.DELETE)
    public ResponseEntity<String> destory(
    	@PathVariable("userId") 
    	String userId) {
        return ResponseUtil.getResEntityForDel(userService.delete(userId));
    }

    /**
     * 批量删除(该方法是自动生成的，只适合单表操作)
     * @param primaryKeys
     * @return
     */
    @RequestMapping(value = "/deletes", method = RequestMethod.DELETE)
    public ResponseEntity<String> deletes(
    	@RequestParam("primaryKeys") 
    	String[] primaryKeys) {
        return ResponseUtil.getResEntityForDel(userService.batchDelete(primaryKeys));
    }
    
    /**
	 * 删除user
	 * */
	@RequestMapping(value = "/userDel", method=RequestMethod.POST)
	public ResponseEntity<String> deleteUsers(
			@RequestParam("userIds")
			String[] userIds) {
		
		if (userIds == null || userIds.length == 0)			
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		return ResponseUtil.getResEntityForGetAndJson(userService.deleteUsers(userIds));
	}
    
    
    /**
	 * 修改密码
	 * */
	@RequestMapping(value = "/password", method=RequestMethod.PUT)
	public ResponseEntity<String> updatePassword(
			String oldPassword,
			String password,
			LoginInfoDTO loginInfoDTO, BindingResult errors) {
		
		if (StringUtil.isNullOrEmpty(password) || StringUtil.isNullOrEmpty(password) || errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		JSONObject json = new JSONObject();
		json.put("status", userService.updatePassword(loginInfoDTO,password,oldPassword));
		
		return ResponseUtil.getResEntityForGet(json.toJSONString());
	}
	
	/**
	 * 根据userId启用用户
	 * */
	@RequestMapping(value = "/userStart", method=RequestMethod.PUT)
	public ResponseEntity<String> startUser(
			@RequestParam("userId")
			String userId) {
		
		if (userId == null )
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		if(userService.startUserById(userId))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		
		return ResponseUtil.getResEntityForPPPWhenFail();
	}
	
	/**
	 * 根据userId禁用用户
	 * */
	@RequestMapping(value = "/userForbidden", method=RequestMethod.PUT)
	public ResponseEntity<String> forbiddenUser(
			@RequestParam("userId")
			String userId){
		
		if (userId == null )
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		if(userService.forbiddenUserById(userId))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		
		return ResponseUtil.getResEntityForPPPWhenFail();
	}
	
	/**
	 * 判段用账号是否重复(true为重复，false为不重复)
	 * */
	@RequestMapping(value = "/userCodeDC", method=RequestMethod.POST)
	public ResponseEntity<String> duplicateCheckingUserName(
			@RequestParam("validationDate")
			String validationDate){
		
		if (StringUtil.isNullOrEmpty(validationDate))
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		JSONObject json = new JSONObject();
		json.put("state", userService.duplicateCheckingUserCode(validationDate));
		
		return ResponseUtil.getResEntityForGet(json.toString());
	}
	
	/**
	 * 判段用户名是否重复(true为重复，false为不重复)
	 * */
	@RequestMapping(value = "/userNameDC", method=RequestMethod.POST)
	public ResponseEntity<String> duplicateCheckingUserCode(
			@RequestParam("validationDate")
			String validationDate){
		
		if (StringUtil.isNullOrEmpty(validationDate))
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		JSONObject json = new JSONObject();
		json.put("state", userService.duplicateCheckingUserName(validationDate));
		
		return ResponseUtil.getResEntityForGet(json.toString());
	}
	
	/**
	 * 判断当前登录人密码是否是初始密码
	 * */
	@RequestMapping(value = "/password/judgement", method=RequestMethod.GET)
	public ResponseEntity<String> judgePassword(
			@Validated
			LoginInfoDTO loginInfoDTO, BindingResult errors){
		if (errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		if (userService.judgePassword(loginInfoDTO))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		
		return ResponseUtil.getResEntityForGetWhenFail();
		
	}
	
	/**
	 * 得到当前登录人的信息
	 * */
	@RequestMapping(value = "/loginInfo", method=RequestMethod.GET)
	public ResponseEntity<String> getLoginInfo(
			@Validated
			LoginInfoDTO loginInfoDTO, BindingResult errors) {
		if (errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		return ResponseUtil.getResEntityForGetAndJson(userService.getToken(loginInfoDTO));
	}
	
	/**
	 * 修改用户基本信息
	 * */
	@RequestMapping(value = "/baseInfo", method=RequestMethod.PUT)
	public ResponseEntity<String> updateBaseInfo(
			@Validated
			LoginInfoDTO loginInfoDTO, BindingResult lgErrors,
			@Validated(GroupForUpdateExtra.class)
			UserDTO userDTO, BindingResult uErrors){
		
		if (lgErrors.hasErrors() || uErrors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		JSONObject json = new JSONObject();
		json.put("status", userService.updateUser(loginInfoDTO, userDTO));
		
		return ResponseUtil.getResEntityForGet(json.toJSONString());
	}
	
	/**
	 * 得到所有的角色
	 * */
	@RequestMapping(value = "/role", method=RequestMethod.GET)
	public ResponseEntity<String> getRole() {
		//这里以后可能要根据登录人的信息来判断，现在先
		List<Map<String, Object>> users = userService.getRole();
		
		return ResponseUtil.getResEntityForGetAndJsonArray(users);
	}
	
	
	/**
	 * 新增一个学生用户
	 */
	@RequestMapping(value = "addUser", method = RequestMethod.POST)
    public ResponseEntity<String> addUser(
        @Validated
        UserDTO userDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        //User userModel = userDTO.toModel();

        return ResponseUtil.getResEntityForPPP(userService.userAdd(userDTO));
    }
    
}
